package com.sinopec.basemodule.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.provider.Browser;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.sinopec.basemodule.BaseApplication;
import com.sinopec.basemodule.BuildConfig;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.router.ReflectUtils;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * author ronny
 * created on 2018/3/21
 */

public class CommonUtils {
    public static boolean isDebug(Context context) {
        if (TextUtils.isEmpty(context.getPackageName()))
            return false;
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
            return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    //弹出消息
    public static void showToast(final Context context, final String msg) {
        if (EmptyUtils.isEmpty(msg) || EmptyUtils.isNull(context)) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                Looper.loop();
            }
        }).start();
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeyboard(AppCompatActivity activity, EditText... editTexts) {
        if (activity == null || editTexts == null || editTexts.length == 0) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        for (EditText ed : editTexts) {
            if (imm.isActive(ed)) {  //i(imm.isActive())  //一直是true
                //imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);//显示或隐藏软键盘
                imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);//隐藏软键盘
                //imm.showSoftInput(myEditText, 0);//显示软键盘
                /* mOrderTimeLl.requestFocus();
                mOrderTimeLl.setFocusableInTouchMode(true);*/
                ed.clearFocus();
                ed.setSelected(false);
            }
        }
    }

    /**
     * 显示软键盘
     */
    public static void showKeyboard(AppCompatActivity activity, EditText editText) {
        if (activity == null || editText == null) {
            return;
        }
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        imm.showSoftInput(editText, 0);
    }

    /**
     * 正则匹配
     *
     * @param regex 正则
     * @param s     字符串
     */
    public static boolean matches(String regex, String s) {
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(s);
        if (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 是否有摄像头
     */
    public static boolean hasCamera() {
        //PackageManager pm = GetApplication.get().getApplicationContext().getPackageManager();
        //pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)--pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)
        if (Camera.getNumberOfCameras() > 0) {
            Logger.e("123===", "具有摄像头！");
            return true;
        }
        Logger.e("123===", "不具有摄像头！");
        return false;
    }

    /**
     * 拨打电话
     */
    public static Disposable callPhone(AppCompatActivity activity, String phoneNumber) {
        if (activity == null) {
            return null;
        }
        return new RxPermissions(activity)
                .request(Manifest.permission.CALL_PHONE)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            if (TextUtils.isEmpty(phoneNumber) || phoneNumber.equals("null")) {
                                ToastUtils.showToast("电话号码为空！");
                            } else {
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
                                activity.startActivity(intent);
                            }
                        } else {
                            ToastUtils.showToast("您已禁止拨打权限，需要重新开启。");
                        }
                    }
                });
    }

    public static void openPDFInFile(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        //intent.addCategory(Intent.CATEGORY_DEFAULT);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            //Android 7.0之后
            StringBuilder sb = new StringBuilder("com.yelo.scandevice");
            if (BuildConfig.isDebug) {
                sb.append(".inhouse");
            }
            sb.append(".fileprovider");
            uri = FileProvider.getUriForFile(context, sb.toString() , file);
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);//给目标文件临时授权
        } else {
            uri = Uri.fromFile(file);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/pdf");
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Logger.w("123===", "Activity was not found for intent, " + intent.toString());
        }
    }

    /**
     * @author lwj
     * @Description: （APP外部打开，适用于加载本地PDF）
    */
    public static void openPDFInNative(Context context, String FILE_NAME) {
        File file = new File(context.getExternalCacheDir(),FILE_NAME);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/pdf");
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            //Log.w("URLSpan", "Activity was not found for intent, " + intent.toString());
        }
    }

    /**
     * @author lwj
     * @Description: 使用浏览器打开PDF：（APP外部打开，适用于加载网络PDF）
     */
    public static void openPDFInBrowser(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(uri, "application/pdf");
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
       // intent.setDataAndType(uri, "application/pdf");
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Log.w("error", "Activity was not found for intent, " + intent.toString());
        }
    }

    /**
     * 是否需要重新登录
     * @param code 错误编码
     * @param msg 错误信息
     */
    public static void isNeedLogin(Context context,int code, String msg) {
        if (code >= 4001 && code <= 4008) {
            ToastUtils.showToast("您的登录信息已发生改变，请重新登录！");
            ReflectUtils.navigationToLogin(context);
            BaseApplication.getInstance().exit();
        }else{
            ToastUtils.showToast(msg);
        }
    }
}
